﻿using System;
using System.Data.SqlClient;
using System.Xml.Serialization;
using System.Diagnostics;

namespace SQLDeployAnything.Data.Environment
{
    [Serializable]
    [XmlRoot(ElementName="SQLConnection")]
    public class SQLConnection : Connection
    {

        private string mSQLServer;
        private string mDatabaseName;
        private bool mTrusted;
        private string mSqlUser;
        private string mSqlPassword;
        private string mFailOverPartner;

        [XmlAttribute(AttributeName="DataSource")]
        public string SQLServer 
        { 
            get { return mSQLServer; }
            set
            {
                if (!string.Equals(value, mSQLServer, StringComparison.InvariantCultureIgnoreCase))
                {
                    mSQLServer = value;
                    OnPropertyChanged("SQLServer");
                }
            }
        }

        [XmlAttribute(AttributeName="FailOverPartner")]
        public string FailOverPartner
        { 
            get { return mFailOverPartner; }
            set
            {
                if (!string.Equals(value, mFailOverPartner,StringComparison.InvariantCultureIgnoreCase))
                {
                    mFailOverPartner = value;
                    OnPropertyChanged("FailOverPartner");
                }
            }
        }

        [XmlAttribute(AttributeName="InitalCatalog")]
        public string Database 
        { 
            get { return mDatabaseName; }
            set
            {
                if (!string.Equals(mDatabaseName, value, StringComparison.InvariantCultureIgnoreCase))
                {
                    mDatabaseName = value;
                    OnPropertyChanged("Database");
                }
            }
        }

        [XmlAttribute(AttributeName="IntergratedSecurity")]
        public bool UseTrustedConnection 
        { 
            get { return mTrusted; }
            set
            {
                if (value != mTrusted)
                {
                    mTrusted = value;
                    OnPropertyChanged("UseTrustedConnection");
                }
            }
        }

        [XmlAttribute(AttributeName="UserId")]
        public string SQLUser 
        { 
            get { return mSqlUser; }
            set
            {
                if (!string.Equals(value, mSqlUser, StringComparison.InvariantCultureIgnoreCase))
                {
                    mSqlUser = value;
                    OnPropertyChanged("SQLUser");
                }
            }
        }

        [XmlAttribute(AttributeName="Password")]
        public string SQLUserPassword 
        { 
            get { return mSqlPassword; }
            set
            {
                mSqlPassword = value;
                OnPropertyChanged("SQLUserPassword");
            }
        }

        [XmlIgnore()]
        public string SQLConnectionString
        {
            get
            {
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                builder.DataSource = mSQLServer;
                builder.InitialCatalog = mDatabaseName;
                if (mTrusted)
                {
                    builder.IntegratedSecurity = true;
                } 
                else 
                {
                    builder.IntegratedSecurity = false;
                    builder.UserID = mSqlUser;
                    builder.Password = mSqlPassword;
                }
                builder.ApplicationName="SQL Deploy Anything - Deployment Connection";
                builder.MaxPoolSize = 100;
                builder.MultipleActiveResultSets = false;
                if (mFailOverPartner != null)
                {
                    builder.FailoverPartner = mFailOverPartner;
                }
                return builder.ConnectionString;
            }
        }

        private bool mValidated = false;
        protected override bool Validate()
        {
            if (!mValidated)
            {
                System.Data.SqlClient.SqlConnection testCon = new System.Data.SqlClient.SqlConnection(this.SQLConnectionString);
                int isAdmin = 0;
                try
                {
                    SqlCommand cm = new SqlCommand("SELECT IS_SRVROLEMEMBER('sysadmin')", testCon);
                    testCon.Open();
                    isAdmin = System.Convert.ToInt32(cm.ExecuteScalar());
                    if (isAdmin == 1)
                    {
                        mValidated = true;
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Unable to validation Connection {0}.  Due to Error: {1}", this.ConnectionName, ex.Message);
                }
                finally
                {
                    if (testCon != null && testCon.State == System.Data.ConnectionState.Open)
                        testCon.Close();
                }
            }
            return mValidated;
        }

        public override string ConnectionTypeHeading
        {
            get { return "SQL Connections"; }
        }

        public override string ConnectionDetails
        {
            get 
            {
                return string.Format("SQL Server: {0}, Database: {1}, User: {2}", 
                    new Object[] { this.SQLServer, this.Database, 
                        (this.UseTrustedConnection ? System.Environment.UserName : this.SQLUser) });
            }
        }
    }
}
